package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.Friend;
import com.itheima.domain.mongo.UserLike;
import com.itheima.service.mongo.FriendService;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author Guanxing
 * @date 2021/9/26
 */
@Service
public class FriendServiceImpl implements FriendService {

    @Autowired
    private MongoTemplate mongoTemplate;

    //添加联系人
    @Override
    public void addContacts(Long loginUserId, Long friendId) {
        //添加我和对方的关系
        Query query1 = new Query(
                Criteria.where("userId").is(loginUserId)
                        .and("friendId").is(friendId)
        );
        Friend friend1 = mongoTemplate.findOne(query1, Friend.class);

        //若果没有我与对方没有关系
        if (friend1 == null) {
            friend1 = new Friend();
            friend1.setUserId(loginUserId);
            friend1.setFriendId(friendId);
            friend1.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend1);
        }

        //添加对方和我的朋友关系
        Query query2 = new Query(
                Criteria.where("userId").is(friendId)
                        .and("friendId").is(loginUserId)
        );
        Friend friend2 = mongoTemplate.findOne(query2, Friend.class);

        //若果没有对方与我没有关系
        if (friend2 == null) {
            friend2 = new Friend();
            friend2.setUserId(friendId);
            friend2.setFriendId(loginUserId);
            friend2.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend2);
        }
    }

    //查询联系人列表
    @Override
    public PageBeanVo findContactList(Integer pageNum, Integer pageSize, Long loginUserId) {
        int startIndex = (pageNum-1)*pageSize;
        Query query = new Query(
                Criteria.where("userId").is(loginUserId)
        ).skip(startIndex).limit(pageSize);
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        long count = mongoTemplate.count(query, Friend.class);
        return new PageBeanVo( pageNum, pageSize , count , friendList);
    }

    //删除好友
    @Override
    public void deleteFriend(Long loginUserId, Long likeUserId) {
        //删除当前用户和她
        Query query1 = new Query(
                Criteria.where("userId").is(loginUserId)
                        .and("friendId").is(likeUserId)
        );
        mongoTemplate.remove(query1, Friend.class);

        //删除她和当前用户
        Query query2 = new Query(
                Criteria.where("userId").is(likeUserId)
                        .and("friendId").is(loginUserId)
        );
        mongoTemplate.remove(query2, Friend.class);
    }
}
